package com.ls.blog.security.filter;

import com.ls.blog.DTO.UserDetailsDTO;
import com.ls.blog.entity.UserInfo;
import com.ls.blog.utils.JwtUtils;
import com.ls.blog.utils.UserUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @program: blog
 * @author: lishun
 * 对于非登录请求判断是否已经有token,有就自动登录
 * @create: 2021-09-19 22:14
 **/

@Slf4j
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private UserUtils userUtilsl;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.info("---------------------jwt校验token过滤器---------------------");
        String jwt = request.getHeader(jwtUtils.getHeader());
        if (StringUtils.isBlank(jwt)){
            chain.doFilter(request,response);
            return;
        }
        Claims claim = jwtUtils.getClaimByToken(jwt);
        if (claim==null){
            throw new JwtException("token异常");
        }
        if (jwtUtils.isTokenExpired(claim)){
            throw new JwtException("token过期");
        }
       UserInfo currentUser = userUtilsl.getLoginUser();
        // redis校验
        if (Objects.isNull(currentUser)){
            throw  new JwtException("token不存在");
        }
        // 更新user信息
        updateUser();
        String username = claim.getSubject();
        UsernamePasswordAuthenticationToken token
                = new UsernamePasswordAuthenticationToken(username,null,null);
        SecurityContextHolder.getContext().setAuthentication(token);
        chain.doFilter(request,response);
    }

    @Async
    void updateUser() {

    }


}
